package com.ywl.study.transaction.aspect;

import com.ywl.study.transaction.annotation.GlobalTransaction;
import com.ywl.study.transaction.netty.NettyClient;
import com.ywl.study.transaction.transaction.DistirctTransactionManager;
import com.ywl.study.transaction.transaction.TransactionType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 先进这个切面，再进@Transaction切面
 */
@Component
@Aspect
@Slf4j
public class DistrictTransactionAspect implements Ordered {

    @Around("@annotation(com.ywl.study.transaction.annotation.GlobalTransaction)")
    public void invoke(ProceedingJoinPoint point) throws Exception {
        log.info("进入DistrictTransactionAspect切面。。。。。");
        MethodSignature signature= (MethodSignature) point.getSignature();
        Method method=signature.getMethod();
        GlobalTransaction globalTransaction= method.getAnnotation(GlobalTransaction.class);
        if(globalTransaction!=null && globalTransaction.isStart()){
            //创建一个全局事务
            String groupId= DistirctTransactionManager.getOrCreateGroup();
            try{
                //执行@Transacdtion标注的方法,会自动调用commit或者rollback方法-->commit ,rollback需要阻塞并等待
                //全局事务管理器返回信号以后，再进行commit或者rollback
                point.proceed();
//                DistirctTransactionManager.addDistrictTransaction(groupId, TransactionType.COMMIT);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
//                DistirctTransactionManager.addDistrictTransaction(groupId, TransactionType.ROLLBACK);
            }finally {
                DistirctTransactionManager.sendTxOver();
            }
        }

    }

    @Override
    public int getOrder() {
        return 99999;
    }
}
